//
//  friendListVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/7/22.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "friendListVC.h"
#import "searchContactsCell.h"
#import "thirdPersonVC.h"
#import "goveDetailVC.h"
@interface friendListVC ()

@property (nonatomic, strong) NSMutableArray *addressBookArray; // 存放所有的联系人信息
@property(nonatomic,strong)NSMutableArray *indexArray;//索引
@property(nonatomic,strong)NSMutableArray *letterResultArr;//title

@property (strong, nonatomic) NSMutableArray * nameArr;
@property (strong, nonatomic)NSMutableDictionary * modelDict;

@property (strong, nonatomic) NSMutableDictionary *mutableDict;
@end

static NSString * searchContactscell = @"searchContactsCell";

@implementation friendListVC

- (NSMutableDictionary *)mutableDict {
    if (!_mutableDict) {
        _mutableDict = [NSMutableDictionary dictionary];
    }
    return _mutableDict;
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航栏title的字体大小等
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:19],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName, nil]];
    self.title = @"好友列表";
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexTrackingBackgroundColor=[UIColor clearColor];
    
    self.addressBookArray = [[NSMutableArray alloc] init];
    self.nameArr = [[NSMutableArray alloc] init];
    self.indexArray = [[NSMutableArray alloc] init];
    _modelDict = [NSMutableDictionary dictionary];
    
    // 注册
    UINib * nib = [UINib nibWithNibName:@"searchContactsCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:searchContactscell];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    [self sendRequest];
}

-(void)leftBarButtonItemClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{

        return self.indexArray;
   
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:self.indexArray.count];

    return self.indexArray.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [[self.letterResultArr objectAtIndex:section] count];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{

        return index;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75.0;
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//
//        NSString *key = [self.indexArray objectAtIndex:section];
//        return key;
//}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 0;

}

//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//
//    return 20;
//
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    view.backgroundColor = RGB(247, 247, 247);
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, 2, screenW, 21)];
    
    titleLabel.textColor = RGB(117, 117, 117);
    titleLabel.font = [UIFont systemFontOfSize:14];
     NSString *key = [self.indexArray objectAtIndex:section];
    titleLabel.text = key;

    [view addSubview:titleLabel];
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    searchContactsCell *cell = [tableView dequeueReusableCellWithIdentifier:searchContactscell forIndexPath:indexPath];
    
    NSString * name = [[self.letterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
    
    NSDictionary * dict = [_modelDict valueForKey:name];
    
    cell.lineView.hidden = YES;
    
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:dict[@"headPhoto"]]];
    cell.headImg.layer.masksToBounds = YES;
    cell.headImg.layer.cornerRadius = 5.0f;
    
    //头像上的按钮
    NSInteger tagInt = [dict[@"userId"] integerValue];
    self.mutableDict[@(tagInt)] = dict[@"userType"];
    cell.headBtn.tag = tagInt;
    [cell.headBtn addTarget:self action:@selector(cellHeadBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    if ([dict[@"userName"] isEqualToString:@""] || [dict[@"userName"] isEqualToString:@"null"]) {
        cell.nameLabel.text = dict[@"account"];
    }else{
        cell.nameLabel.text = dict[@"userName"];
    }
    
    CGSize size = [cell.nameLabel sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    if (size.width<190) {
        [cell.nameLabel setFrame:CGRectMake(cell.nameLabel.x, cell.nameLabel.y, size.width, cell.nameLabel.height)];
    }else{
        [cell.nameLabel setFrame:CGRectMake(cell.nameLabel.x, cell.nameLabel.y, 168, cell.nameLabel.height)];
    }
    
    cell.lineView.x = cell.nameLabel.x + cell.nameLabel.width + 2;
    
    

    if ([dict[@"positionName"] isEqualToString:@""] || [dict[@"positionName"] isEqualToString:@"null"]) {
        cell.posName.text = @"";
    }else{
        cell.posName.text = dict[@"positionName"];
    }
    CGSize posSize = [cell.posName sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    if (posSize.width <= 60) {
        cell.posName.width = posSize.width;
    }else{
        cell.posName.width = 60;
    }

    
    cell.posName.x = cell.lineView.x;
    cell.vImg.x = cell.posName.x + cell.posName.width + 2;
    if (cell.vImg.x > 185) {
        cell.vImg.x = 184;
    }
    

    cell.lineview.hidden = YES;
    //上级
    cell.detailLabel.text = [UsedTool userType:dict[@"userType"] companyName:dict[@"companyName"] userAddress:dict[@"userAddress"]];
    
//    if ([dict[@"authState"]integerValue] == 2) {
//        cell.vImg.image = [UIImage imageNamed:@"yirenzheng"];
//    }else{
//        cell.vImg.image = [UIImage imageNamed:@"weirenzheng"];
//    }
    //认证
    cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:dict[@"authState"]];
    //会员图标
    cell.vImg.image = [UsedTool setVipimage:dict[@"vipLevel"]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    
    NSString * name = [[self.letterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
    
    NSDictionary * dict = [_modelDict valueForKey:name];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    manager.shouldResignOnTouchOutside = NO;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.enableAutoToolbar = NO;
    
    sessionVC *chatVc = [[sessionVC alloc] init];
    chatVc.title = dict[@"userName"];
    chatVc.conversationType = ConversationType_PRIVATE;
    chatVc.targetId = dict[@"account"];
    chatVc.enableUnreadMessageIcon = YES;
    chatVc.enableNewComingMessageIcon = YES;
    chatVc.defaultHistoryMessageCountOfChatRoom = 50;
    
    self.tabBarController.tabBar.hidden = YES;
    
    [self.navigationController pushViewController:chatVc animated:YES];
    
    
}
#pragma mark - 点击头像跳转三人称界面
- (void)cellHeadBtn: (UIButton *)sender {
    if ([self.mutableDict[@(sender.tag)] integerValue] == 3) {
        goveDetailVC * goveVC = [[goveDetailVC alloc]init];
        goveVC.userId = [NSString stringWithFormat:@"%ld",sender.tag];
        goveVC.userType = self.mutableDict[@(sender.tag)];
        [self.navigationController pushViewController:goveVC animated:YES];
    }else{
        thirdPersonVC *thirdVC = [[thirdPersonVC alloc] init];
        thirdVC.userId = [NSString stringWithFormat:@"%ld",sender.tag];
        thirdVC.userType = self.mutableDict[@(sender.tag)];
        [self.navigationController pushViewController:thirdVC animated:YES];
    }
}

#pragma mark - 请求数据

-(void)sendRequest{
    
    [self showRoundProgressWithTitle:@"请稍后..."];
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];

    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getMyFriend_app_social.im.lensum"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//                            NSString * jsonStr = [LSHttpTool DataTOjsonString:dicInfo];
//                                        NSLog(@"--------------------json:%@",jsonStr);
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            self.addressBookArray = dicInfo[@"data"][@"record"];
            
            //解析数据
            for (NSDictionary * dict in self.addressBookArray) {
                
                [self.nameArr addObject:dict[@"userName"]];
                [_modelDict setValue:dict forKey:dict[@"userName"]];
                
            }
            
            self.indexArray = [ChineseString IndexArray:_nameArr];
            self.letterResultArr = [ChineseString LetterSortArray:_nameArr];
            
            [self hideBubble];
            
        }else {

            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
        }
        
        [self.tableView reloadData];
        [self hideBubble];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self showSingleIconBubble:error.localizedDescription];
    }];


}

@end
